package com.starsky.common.kafka.service;

import com.starsky.common.data.RstData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

/**
 * kafka发送工具类
 */
@Slf4j
@Component
public class KafkaProductService {
    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 发送消息到kafka队列
     * @param topic
     * @param message
     * @return
     */
    public RstData sendKafka(String topic, String message) {
        try {
            log.info("kafka的消息: {}", message);
//            异步发送
            kafkaTemplate.send(topic, "key", message).get();;
            //  同步发送，默认异步
            kafkaTemplate.send(topic, "key", message);;
            log.info("发送kafka成功.");
        } catch (Exception e) {
            log.error("发送kafka失败", e);
            return RstData.faild("发送kafka失败: " + e);
        }
        return RstData.success();
    }

}
